package org.ahead4.joint.utils;

import okhttp3.*;
import okio.BufferedSink;
import org.ahead4.joint.task.SendScheduleTask;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;

/**
 * @author WangYu
 * @title: OkHttpUtils
 * @description: TODO
 * @date 2020/3/1315:02
 */
public class OkHttpUtils {

    private static final Log logger = LogFactory.getLog(SendScheduleTask.class);
    /**
     * OkHttp客户端实例全局共享
     */
    private static final OkHttpClient okHttpClient = new OkHttpClient();


    public static String syncPostJSON(String url, String data) throws IOException {
        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return MediaType.parse("application/json;charset=UTF-8");
            }

            @Override
            public void writeTo(BufferedSink bufferedSink) throws IOException {
                bufferedSink.writeUtf8(data);
            }

        };
        Request request = new Request.Builder()
                .url(url)//请求接口。如果需要传参拼接到接口后面。
                .post(requestBody)
                .build();//创建Request 对象
        Response response = okHttpClient.newCall(request).execute();//得到Response 对象
        if (!response.isSuccessful()) {
            String message = "code:" + response.code() + ";message:" + response.message();
            logger.error(message);
            throw new RuntimeException(message);
        }
        return response.body().string();
    }
}
